package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Jt
 * @date 2021/4/14 14:56
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Resource
    private FileStorageService fileStorageService;

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.profix}")
    String profix;
    @Value("${file.oss.endpoint}")
    String endpoint;
    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 上传图片
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
//        1.参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"请上传正确的图片");
        }
//        获取当前登录用户(userId)
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH,"请先登录在上传");
        }
//        2.上传到oss
        try {
//            设置文件的名称
            String fileName = UUID.randomUUID().toString().replace("-", "");
//            截取原文件后缀名
            String oriName = multipartFile.getOriginalFilename();
            String suffix = oriName.substring(oriName.lastIndexOf("."));
            String fileId = fileStorageService.store(profix, fileName + suffix, multipartFile.getInputStream());
//            创建素材信息并保存
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());
            wmMaterial.setUrl(fileId);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);// 保存素材信息
            wmMaterial.setUrl(webSite+fileId);
//            返回结果
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            log.error("上传图片出现异常 ===> {}",e);
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"上传图片出现异常");
        }
    }

    /**
     * 查询列表
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult findLit(WmMaterialDto wmMaterialDto) {
//        1.检查参数
        wmMaterialDto.checkParam(); // 检查分页
//        2.判断是否登录
        Integer userId = WmThreadLocalUtils.getUser().getId();
//        3.查询数据
//        分页条件
        Page<WmMaterial> wmMaterialPage = new Page(wmMaterialDto.getPage(),wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQuery = Wrappers.lambdaQuery();
        if (wmMaterialDto.getIsCollection() != null && wmMaterialDto.getIsCollection().intValue() == 1) {
            lambdaQuery.eq(WmMaterial::getIsCollection,wmMaterialDto.getIsCollection());
        }
        lambdaQuery.eq(WmMaterial::getUserId,userId);
        lambdaQuery.orderByDesc(WmMaterial::getCreatedTime);
//        执行查询
        IPage<WmMaterial> page = page(wmMaterialPage, lambdaQuery);
        PageResponseResult result = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(), (int) page.getTotal());
//        为图片路径添加访问前缀
        List<WmMaterial> records = page.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }
        result.setData(records);
        return result;
    }

    /**
     * 删除图片
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
//        1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//        2.根据素材id + 登录用户id 查询素材信息
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        WmMaterial material = getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, user.getId()));
        if (material == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        3.根据素材id查询关联表中是否有引用 , 如果有,则不能删除
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH,"该素材无法删除,因已被引用");
        }
//        4.删除素材和OSS中对应的素材
        removeById(id);
        fileStorageService.delete(material.getUrl());
        return ResponseResult.okResult();
    }

    /**
     * 收藏与取消收藏
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
//        1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//        2.登录用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
//        修改操作
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type)
        .eq(WmMaterial::getId,id)
        .eq(WmMaterial::getUserId,user.getId()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
